package com.walkline.weather;

import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.io.transport.ConnectionFactory;

import com.walkline.app.WeatherAppConfig;
import com.walkline.util.Function;
import com.walkline.util.StringUtility;
import com.walkline.util.network.HttpClient;
import com.walkline.weather.dao.YahooPlaces;
import com.walkline.weather.dao.YahooWeather;
import com.walkline.weather.inf.Places;
import com.walkline.weather.inf.Weather;

public class WeatherSDK
{
	protected String APPKEY = "d75471a0835134305ee35929ddc30dbcedea4e60";
	protected int MAX_RESULT_SIZE = 200;
	protected ConnectionFactory _cf;
	protected HttpClient _http;

	public static WeatherSDK getInstance() {return new WeatherSDK();}

	protected WeatherSDK()
	{
		_cf = new ConnectionFactory();
		_cf.setPreferredTransportTypes(WeatherAppConfig.preferredTransportTypes);
		_cf.setDisallowedTransportTypes(WeatherAppConfig.disallowedTransportTypes);
		_cf.setTimeoutSupported(true);
		_cf.setAttemptsLimit(10);
		_cf.setRetryFactor(2000);
		_cf.setConnectionTimeout(120000);

		_http = new HttpClient(_cf);
	}

	private Weather getWeather(StringBuffer sb) throws WeatherException {return new YahooWeather(this, sb);}
	public Weather getWeather(String woeid, String unit) throws WeatherException {return getWeather(woeid, unit, null, null);}
	public Weather getWeather(final String woeid, final String unit, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Weather result = null;
						result = getWeather(woeid, unit);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Weather result = null;
			Hashtable params = new Hashtable();

			params.put("w", woeid);
			params.put("u", unit);

			StringBuffer sb = new StringBuffer();
			try {
				sb = doRequest(WeatherAppConfig.queryWeatherRssRequestURL, params);

				if (sb == null) {
					result = null;
				} else {
					result = getWeather(sb);
				}
			} catch (WeatherException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}

	private Places getPlaces(StringBuffer sb) throws WeatherException {return new YahooPlaces(this, sb);}
	public Places getPlaces(String place) throws WeatherException {return getPlaces(place, null, null);}
	public Places getPlaces(final String place, final AsyncCallback listener, final Object state)
	{
		if (listener != null) {
			new Thread() {
				public void run() {
					try {
						Places result = null;
						result = getPlaces(place);
						listener.onComplete(result, null);
					} catch (Exception e) {
						listener.onException(e, null);
					}
				}
			}.start();

			return null;
		} else {
			Places result = null;
			StringBuffer queryStringBuffer = new StringBuffer();
			Hashtable params = new Hashtable();

			queryStringBuffer.append("(").append(StringUtility.encode(place)).append("%2A)").append(";count=").append(MAX_RESULT_SIZE);

			params.put("lang", "zh-CN");
			params.put("appid", APPKEY);

			StringBuffer sb = new StringBuffer();
			try {
				sb = doRequest(WeatherAppConfig.queryPlaceRequestURL + queryStringBuffer.toString(), params);

				if (sb == null) {
					result = null;
				} else {
					result = getPlaces(sb);
				}
			} catch (WeatherException e) {Function.errorDialog(e.toString());}

			return result;
		}
	}





//**************************************************************************************************
//
//             //              //      //    //      ////////////////            //      //        
//             //            //    //  //  //                    //          //  //  //  //        
// //////////  //          //////////  ////        //          //      //        //      //        
//     //    ////////////              //      //  //  //    //    //  //  ////////////  ////////  
//     //      //      //    ////////    ////////  //    //  //  //    //      ////    //    //    
//     //      //      //    //    //              //        //        //    //  ////    //  //    
//     //      //      //    ////////  //          //    //  //  //    //  //    //  //  //  //    
//     //      //      //    //    //  //    //    //  //    //    //  //      //        //  //    
//     ////////        //    ////////  //  //      //        //        //  //////////    //  //    
// ////      //        //    //    //  ////    //  //      ////        //    //    //      //      
//         //          //    //    //  //      //  //                  //      ////      //  //    
//       //        ////      //  ////    ////////  //////////////////////  ////    //  //      //  
//
//**************************************************************************************************

	/*
	private byte[] doRequestRAW(String woeid, String unit) throws Exception
	{
		byte[] result = null;
		StringBuffer responseBuffer = null;

		try {
			responseBuffer = _http.doGet(woeid, unit);				

			if ((responseBuffer == null) || (responseBuffer.length() <= 0)) {result = null;}

			result = responseBuffer.toString().getBytes();
		} catch (Exception e) {throw new Exception(e.getMessage());}

		return result;
	}
	*/

	private StringBuffer doRequest(String api, Hashtable param) throws WeatherException
	{
		StringBuffer responseBuffer = null;

		try {
			responseBuffer = _http.doGet(api, param);

			//if (responseBuffer == null) {result = null;}

			//Function.errorDialog(responseBuffer.toString());
			//result = new JSONObject(new JSONTokener(responseBuffer.toString()));
		} catch (Exception e) {
			throw new WeatherException(e.getMessage());
		} catch (Throwable t) {
			throw new WeatherException(t.getMessage());
		}

		return responseBuffer;
	}
}